package org.speedmall.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.speedmall.common.core.exception.BusinessException;
import org.speedmall.core.entity.Product;
import org.speedmall.core.mapper.ProductMapper;
import org.speedmall.core.service.ProductService;
import org.speedmall.storage.api.bo.ProductDecreaseBO;
import org.speedmall.storage.api.bo.ProductIncreaseBO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author hujiaguo
 * @Package org.speedmall.core.service.impl
 * @date 2024/4/25 18:19:53
 */
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Override
    public void increaseStorage(ProductIncreaseBO increaseBO) {
        Product product = findById(increaseBO.getProductId());
        product.setTotal(product.getTotal() + increaseBO.getCount());
        product.setResidue(product.getResidue() + increaseBO.getCount());
        productMapper.updateById(product);
    }

    @Transactional
    @Override
    public void decreaseStorage(ProductDecreaseBO decreaseBO) {
        Product product = findById(decreaseBO.getProductId());
        if (product.getResidue().compareTo(decreaseBO.getCount()) < 0) {
            throw new BusinessException("产品库存不足");
        }
        product.setUsed(product.getUsed() + decreaseBO.getCount());
        product.setResidue(product.getResidue() - decreaseBO.getCount());
        productMapper.updateById(product);
    }

    @Override
    public Product findById(Long id) {
        return productMapper.selectById(id);
    }

    @Override
    public Product findByParma(Product product) {
        Wrapper<Product> wrapper = new QueryWrapper<>(product);
        return productMapper.selectOne(wrapper);
    }
}
